/**
 * 
 */
package com.guchenbo.example.zip;

import java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

/**
 * 依赖开源框架{@link http://www.lingala.net/zip4j/index.php}
 * 
 * @author Cre.Gu
 *
 */
public class Zip4jTest {

	@Test
	public void test2() {
		zip("C:\\Users\\CreGu\\Contacts", "C:\\Users\\CreGu\\Contacts.zip");
	}

	public static void javaZip(File inFile, ZipOutputStream zos, String parent)
			throws IOException {
		String entryName = parent + "/" + inFile.getName();
		if (StringUtils.isBlank(parent)) {
			entryName = inFile.getName();
		}

		if (inFile.isDirectory()) {
			File[] files = inFile.listFiles();

			for (File file : files)
				javaZip(file, zos, entryName);

			if (files.length == 0) {
				ZipEntry entry = new ZipEntry(entryName + "/");

				zos.putNextEntry(entry);
				zos.closeEntry();
			}

		} else {

			ZipEntry entry = new ZipEntry(entryName);
			zos.putNextEntry(entry);

//			FileUtils.copyFile(inFile, zos);
		}

	}

	public static void zip(String source, String dest) {
		zip(new File(source), new File(dest));
	}

	public static void zip(File home, File dest) {
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别

		try {
			ZipFile zipFile = new ZipFile(dest);
			if (home.isDirectory()) {
				zipFile.addFolder(home, parameters);
			} else {
				zipFile.addFile(home, parameters);
			}
		} catch (ZipException e) {
			e.printStackTrace();
		}
	}
}
